<?php

class Antz_Db_Select
{
    private $useLimit = false;
    private $limit = array('num'=>null, 'start'=>0);
    private $from = array('table'=>'', 'what'=>'');
    private $useWhere = false;
    private $where = array();
    private $useOrder = false;
    private $order = array();
    private $joins = array();
    public function __construct()
    {
        
    }
    
    public function __toString()
    {
        $joins = array();
        foreach($this->joins as $k=>$v){
          $joins[] = ' JOIN '.$v['tablename'].' ON '.$v['on'];
        }
        $q = "SELECT {$this->from['what']} FROM {$this->from['table']} ";
        $q .= implode(' ', $joins);
        if($this->useWhere) $q .= ' WHERE '.implode(' AND ', $this->where).' ';
        if($this->useOrder) $q .= ' ORDER BY '.implode(' , ', $this->order);
        if($this->useLimit) $q .= " LIMIT {$this->limit['num']} OFFSET {$this->limit['start']}";
        return $q;
    }
    
    public function join($tablename, $on){
      $this->joins[] = array('tablename' => $tablename, 'on' => $on);
    }
    
    public function getFromAsArray(){
      return $this->from;
    }
    
    public function from($tablename, $what='')
    {
        $this->from['table'] = $tablename;
        if($what!='') $this->what($what);
        return $this;
    }
    
    public function what($what){
      $this->from['what'] = $what;
      return $this;
    }
    
    public function where($colname, $value, $match='=')
    {
        $this->useWhere = true;
        $this->where[] = $colname.' '.$match." '".mysql_real_escape_string($value)."'";
        return $this;
    }
    
    public function limit($num, $start=0)
    {
        $this->useLimit = true;
        $this->limit['num'] = $num;
        $this->limit['start'] = $start;
        return $this;
    }
    
    public function order($order)
    {
        $this->useOrder = true;
        $this->order[] = $order;
        return $this;
    }
    
        /**
     * Sets the limit and count by page number.
     *
     * @param int $page Limit results to this page number.
     * @param int $rowCount Use this many rows per page.
     * @return void
     */
    public function limitPage($page, $rowCount)
    {
        $page     = ($page > 0)     ? $page     : 1;
        $rowCount = ($rowCount > 0) ? $rowCount : 1;
        $this->limit($rowCount * ($page-1), $rowCount);
        return $this;
        // Zend fw
        $this->_parts['limitCount']  = (int) $rowCount;
        $this->_parts['limitOffset'] = (int) $rowCount * ($page - 1);
        return $this;
    }
    
}
